<?php
namespace app\service;

use think\Log;

class CozeService
{
    /**
     * API密钥
     * @var string
     */
    private $_api_key;
    private $_workflow_id;
    private $_bot_id;
    private $_timeout = 30;
    private $_api_workflow_url = 'https://api.coze.cn/v1/workflow/run';
    private $_api_workflow_histories_url = 'https://api.coze.cn/v1/workflows/:workflow_id/run_histories/:execute_id';
    
    
    /**
     * 构造函数
     */
    public function __construct($api_key, $workflow_id, $bot_id = "",$timeout= 30)
    {
        // 从配置中获取API密钥
        $this->_api_key = $api_key;
        $this->_workflow_id = $workflow_id;
        $this->_bot_id = $bot_id;
        $this->_timeout = $timeout;
        // 参数验证
        if (empty($this->_workflow_id)) {
            throw new \Exception('workflow_id不能为空');
        }
        if (empty($this->_api_key)) {
            throw new \Exception('api_key不能为空');  
        }
    }
    


    
    public function call_workflow($parameters, $is_async = false)
    { 
        if (empty($parameters)) {
            throw new \Exception('parameters不能为空');
        }
        
        // 构建请求数据
        $requestData = [
            'is_async' => $is_async ,
            'workflow_id' => $this->_workflow_id, // 确保为字符串
            'parameters' => $parameters
        ];
        
        // 如果有bot_id，添加到parameters中
        if ($this->_bot_id) {
            $requestData['parameters']['bot_id'] = $this->_bot_id;
        }

        // 设置请求头
        $headers = [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $this->_api_key
        ];
        
        // 将数据转换为JSON字符串
        $jsonData = json_encode($requestData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        
        // debug_dump($jsonData,$headers);
        // 初始化CURL
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->_api_workflow_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData); // 直接发送JSON字符串
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_TIMEOUT, $this->_timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 添加SSL选项
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        // 执行请求
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);
        
        // 检查响应状态
        if ($httpCode !== 200) {
            throw new \Exception('API failed: http code: ' . $httpCode);
        }
        
        // 解析响应数据
        $responseData = json_decode($response, true);

        if (!isset($responseData['data']) || !isset($responseData['code']) || $responseData['code'] !== 0) {
            Log::error('API failed: ' . $response);
            throw new \Exception('API failed: ' . $response);
        }
        $responseData = json_decode($responseData['data'],true);
        $responseData = $responseData['output'];
        $result = json_decode($responseData,true);

        return $result;
    }
    public function get_workflow_histories($execute_id)
    {
        
        $api_url = str_replace(':workflow_id', $this->_workflow_id, $this->_api_workflow_histories_url);
        $api_url = str_replace(':execute_id', $execute_id, $api_url);
        $headers = [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $this->_api_key
        ];
        $requestData = [
            'workflow_id' => (string)$this->_workflow_id, // 确保为字符串
            'execute_id' => $execute_id
        ];
        $jsonData = json_encode($requestData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);


        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, false);
        // curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData); // 直接发送JSON字符串
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_TIMEOUT, $this->_timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 添加SSL选项
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        // 执行请求
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);

        // 检查响应状态
        if ($httpCode !== 200) {
            throw new \Exception('API failed: http code: ' . $httpCode);
        }
        
        // 解析响应数据
        $responseData = json_decode($response, true);
        if (!isset($responseData['code']) || $responseData['code'] !== 0) {
            throw new \Exception('API failed: ' . $response);
        }
        $responseData = $responseData['data'][0];
        
        if ($responseData['execute_status'] == 'Running'){
            return ['code' => 202,'data'=>[]];
        }

        if ($responseData['execute_status'] !== 'Success'){
            throw new \Exception('API failed: ' . $response);
        }

        $responseData = json_decode($responseData['output'],true);


        $responseData = json_decode($responseData['Output'],true);
        // debug_dump($responseData);

        $responseData = json_decode($responseData['output'],true);

        return [
            'code' => 200,
            'data' => $responseData
        ];

    }
} 